package com.qiudaozhang.loveblog.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 处理图片上传图床
 * @author 邱道长
 * 2019/11/13
 */
@Controller
@RequestMapping("up")
public class UploadImageController {

    @Resource
    private RestTemplate restTemplate;

    @PostMapping("image")
    @ResponseBody
    public ResponseEntity<String>  image(@RequestParam("file") MultipartFile multipart) throws IOException {

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        // 设置客户端
        httpHeaders.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        MultiValueMap<String,Object> multiValueMap = new LinkedMultiValueMap<>();
        Path filepath = Paths.get( multipart.getOriginalFilename());
        multipart.transferTo(filepath);
        // 传递文件，通过网络传递，不能直接使用java.io.File，必须用FileSystemResource
        FileSystemResource resource  = new FileSystemResource(filepath.toFile());
        multiValueMap.add("smfile",resource);
        HttpEntity<MultiValueMap<String,Object>> httpEntity = new HttpEntity<>(multiValueMap,httpHeaders);
        String url = "https://sm.ms/api/v2/upload";
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST,httpEntity,String.class);
        return responseEntity;
    }
}
